﻿using Microsoft.AspNetCore.Authorization;

namespace Magic.Core;

/// <summary>
/// 如果整个服务只需要鉴权逻辑是一样的，那么用这个就行了
/// </summary>
public class AuthorizationHandler : IAuthorizationHandler
{
    /// <summary>
    /// 授权验证核心方法
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public virtual async Task HandleAsync(AuthorizationHandlerContext context)
    {
        // 判断是否授权
        var isAuthenticated = context.User.Identity.IsAuthenticated;

        if (!isAuthenticated)
        {
            context.Fail();
        }
        //var userId = context.User.FindFirst("userId")?.Value;
        //Console.WriteLine($"当前登录的用户id：{userId}");
        //if (userId != "666666") {
        //    context.Fail();
        //}

    }


}

/// <summary>
/// 第一个鉴权策略
/// </summary>
public class MagicAuthorizationHandler : AuthorizationHandler<MagicAuthorizationRequirement>
{
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MagicAuthorizationRequirement requirement)
    {
        Console.WriteLine("magic鉴权策略");
        // 判断是否授权
        var isAuthenticated = context.User.Identity.IsAuthenticated;

        if (!isAuthenticated)
        {
            context.Fail();
        }
        context.Succeed(requirement);
        return;
    }
}

/// <summary>
/// 第二个鉴权策略
/// </summary>
public class MagicTestAuthorizationHandler : AuthorizationHandler<MagicTestAuthorizationRequirement>
{
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MagicTestAuthorizationRequirement requirement)
    {
        Console.WriteLine("magicTest鉴权策略");
        context.Fail();
        return;
    }
}




public class MagicAuthorizationRequirement : IAuthorizationRequirement
{

}

public class MagicTestAuthorizationRequirement : IAuthorizationRequirement
{

}